import { fileURLToPath, URL } from 'node:url'
import { terser } from 'rollup-plugin-terser'
import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
import legacy from '@vitejs/plugin-legacy'
import { visualizer } from 'rollup-plugin-visualizer'

export default defineConfig(({ mode, command }) => {
  const env = loadEnv(mode, process.cwd())
  const { VITE_APP_BASE_API, VITE_ORDER_APP_BASE_API } = env
  console.log('env:', env)
  const isBuild = command === 'build'
  return {
    plugins: [
      vue(),
      vueJsx(),
      legacy({
        targets: ['Chrome 64'], // 兼容低版本
        modernPolyfills: true,
      }),
      visualizer({ open: false }), // 打包可视化
      // 添加了：仅在生产环境应用 terser 压缩插件
      // ...(isBuild ? [terser({ compress: { drop_console: true } })] : []),
    ],
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url)),
      },
    },
    server: {
      proxy: {
        [VITE_ORDER_APP_BASE_API]: {
          target: VITE_APP_BASE_API,
          changeOrigin: true,
          rewrite: (p) => p.replace(`${VITE_ORDER_APP_BASE_API}`, ''),
        },
      },
      host: '0.0.0.0',
    },
    // build: {
    //   rollupOptions: {},
    //   esbuild: {
    //     drop: isBuild ? ['console', 'debugger'] : [],
    //   },
    //   target: ['ios11', 'Chrome 64'], // 兼容低版本
    // },
    define: {
      'process.env': {
        VITE_APP_BASE_API: JSON.stringify(VITE_APP_BASE_API),
      },
    },
  }
})
